from django.shortcuts import render
from user_app.models import User
from rest_framework.views import APIView
from rest_framework import generics

from rest_framework.response import Response
from rest_framework import status
from .serializers import RegisterSerializers,UserDetailSerializer
from .utils import generate_token

class LoginView(APIView):
    def post(self,request):
        '''登录功能'''
        #1.获取参数
        phone = request.data.get('phone')
        password = request.data.get('password')
        #2.检验参数
        try:
            user = User.objects.get(phone=phone)
        except User.DoesNotExist:
            return Response({'code':status.HTTP_404_NOT_FOUND,'msg':'用户不存在'})
        #3.返回结果
        if user.check_password(password):
            #生成token
            token = generate_token({'phone':phone})
            return Response({
                'code':status.HTTP_200_OK,
                'msg':'登陆成功',
                'nickname':user.nickname,
                'user_id':user.id,
                'token':token
            })
        else:
            return Response({
                'code':status.HTTP_403_FORBIDDEN,
                'msg':'密码错误'
            })
    def get(self,request):
        pass

class RegisterView(APIView):
    def post(self,request):
        #创建序列化器
        serializers = RegisterSerializers(data=request.data)
        if serializers.is_valid():
            #保存数据
            user = serializers.save()
            #返回响应
            return Response({
                'code':status.HTTP_201_CREATED,
                'msg':'注册成功'
            })
        else:
            return Response({
                'code':status.HTTP_400_BAD_REQUEST,
                #返回序列化器验证的结果
                'msg':f'注册失败:{serializers.errors}'
            })

#获取用户详细信息
class UserDetailView(generics.RetrieveAPIView):
        queryset = User.objects.all()
        serializer_class = UserDetailSerializer
